package com.axinfu.util.validq.validator;

import com.axinfu.util.EmptyUtil;
import com.axinfu.util.validq.BaseValidator;
import com.axinfu.util.validq.ValidatorContext;
import com.axinfu.util.validq.exception.ValidQException;

/**
 * 验证String是否符合正则匹配
 *
 * @author zjn
 * @since 2022/3/23
 */
@SuppressWarnings("unused")
public class StringRegexValidator extends BaseValidator {

    private String regex;

    public StringRegexValidator() {
    }

    public StringRegexValidator(String field, String fieldName) {
        super(field, fieldName);
    }

    public StringRegexValidator(String field, String fieldName, String errorMsg) {
        super(field, fieldName, errorMsg);
    }

    @Override
    public int index() {
        return 6;
    }

    @Override
    public boolean validate(ValidatorContext context, Object target) {
        if (EmptyUtil.isEmpty(target)) {
            return true;
        }
        if (EmptyUtil.isEmpty(regex)) {
            throw new ValidQException("regex string can not be empty");
        }

        String targetData = String.valueOf(target);

        if (targetData.matches(regex)) {
            return true;
        }

        String errorMsg = getDefaultMsg("[%s]格式不正确");

        return fail(context, null, errorMsg);
    }

    public String getRegex() {
        return regex;
    }

    public StringRegexValidator setRegex(String regex) {
        this.regex = regex;
        return this;
    }
}
